import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:loxen/dialog/toast.dart';
import 'package:loxen/mode/user.dart';
import 'package:loxen/utils/config.dart';
import 'package:loxen/utils/image_url.dart';
import 'package:loxen/utils/string_res.dart';
import 'package:loxen/viewmode/base_view_model.dart';
import 'package:loxen/viewmode/user_info_edit_viewmodel.dart';
import 'package:loxen/widget/address_dialog.dart';
import 'package:loxen/widget/empty_widget.dart';
import 'package:loxen/widget/fail_widget.dart';
import 'package:loxen/widget/loading_widget.dart';
import 'package:loxen/widget/my_subassembly.dart';
import 'package:provider/provider.dart';

class MineInfoEditWidget extends StatelessWidget {
  final User user;
  final Map map = {
    '0': '未知',
    '1': '男',
    '2': '女',
  };

  MineInfoEditWidget({Key key, this.user}) : super(key: key);

  final TextEditingController _company = TextEditingController();
  final TextEditingController _position = TextEditingController();
  final TextEditingController _email = TextEditingController();
  final TextEditingController _sign = TextEditingController();
  final TextEditingController _city = TextEditingController();
  final TextEditingController _sexual = TextEditingController();

  final ValueNotifier<String> _nicknameNotifier = ValueNotifier('');
  final ValueNotifier<String> _companyError = ValueNotifier('');
  final ValueNotifier<String> _positionError = ValueNotifier('');
  final ValueNotifier<String> _emailError = ValueNotifier('');
  final ValueNotifier<String> _signError = ValueNotifier('');
  final ValueNotifier<String> _cityError = ValueNotifier('');
  final ValueNotifier<String> _sexualError = ValueNotifier('');

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<UserInfoEditViewModel>(
      create: (_) {
        UserInfoEditViewModel model = UserInfoEditViewModel();
        model.loadData();
        return model;
      },
      child: Scaffold(
        appBar: PreferredSize(
          preferredSize: Size(double.infinity, 95.h),
          child: Container(
            color: Theme.of(context).backgroundColor,
            child: SafeArea(
              child: Column(
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      MySubassembly.getBackIcon(context,
                          color: Theme.of(context).textTheme.subtitle2.color),
                      Expanded(
                        child: Center(
                          child: Text(
                            StringResources.ge_ren_zi_liao,
                            style: TextStyle(
                                fontSize: 32.sp,
                                fontWeight: FontWeight.bold,
                                color: Theme.of(context).textTheme.subtitle2.color),
                          ),
                        ),
                      ),
                      MySubassembly.getSearchIcon(null, text: Text('')),
                    ],
                  )
                ],
              ),
            ),
          ),
        ),
        body: Selector<UserInfoEditViewModel, BaseState>(
            builder: (context, state, _) {
              if (state == BaseState.LOADING) {
                return LoadingWidget();
              }
              if (state == BaseState.CONTENT) {
                var userInfoEdit =
                    Provider.of<UserInfoEditViewModel>(context, listen: false).userInfoEdit;
                var portrait = userInfoEdit.portrait;
                _company.text = userInfoEdit.company;
                _position.text = userInfoEdit.position;
                _email.text = userInfoEdit.email;
                _sign.text = userInfoEdit.sign;
                _city.text = userInfoEdit.city;
                _nicknameNotifier.value = userInfoEdit.nickname;
                var sex = userInfoEdit.sexual;
                print(userInfoEdit.sexual);
                _sexual.text = sex == null || sex.trim() == '' || sex == '0' ? '未选择' : map[sex];
                return Container(
                  decoration: BoxDecoration(
                    border: Border(top: BorderSide(width: 1.h, color: Color(0xFFEBECF1))),
                    color: Theme.of(context).backgroundColor,
                  ),
                  padding: const EdgeInsets.only(left: 47.5, right: 47.5),
                  child: ListView(
                    physics: BouncingScrollPhysics(),
                    children: <Widget>[
                      _renderHeader(context),
                      ValueListenableProvider.value(
                        value: _companyError,
                        builder: (context, _) {
                          String error = context.watch<String>();
                          return _renderTextField(
                            context,
                            StringResources.gong_si,
                            StringResources.qing_shu_ru_gong_si_ming_cheng,
                            _company,
                            'gongsi',
                            error: error,
                          );
                        },
                      ),
                      ValueListenableProvider.value(
                        value: _positionError,
                        builder: (context, _) {
                          String error = context.watch<String>();
                          return _renderTextField(context, StringResources.zhi_wei,
                              StringResources.qing_shu_ru_zhi_wei, _position, 'zhiwei',
                              error: error);
                        },
                      ),
                      ValueListenableProvider.value(
                        value: _emailError,
                        builder: (context, _) {
                          String error = context.watch<String>();
                          return _renderTextField(context, StringResources.you_xiang,
                              StringResources.qing_shu_ru_you_xiang, _email, 'youixang',
                              error: error);
                        },
                      ),
                      ValueListenableProvider.value(
                        value: _signError,
                        builder: (context, _) {
                          String error = context.watch<String>();
                          return _renderTextField(context, StringResources.qian_ming,
                              StringResources.qing_shu_ru_qian_ming, _sign, 'qianming',
                              error: error);
                        },
                      ),
                      ValueListenableProvider.value(
                        value: _cityError,
                        builder: (context, _) {
                          String error = context.watch<String>();
                          return _renderTextField(context, StringResources.cheng_shi,
                              StringResources.qing_xuan_ze_cheng_shi, _city, 'chengshi',
                              error: error, isSelectMode: true);
                        },
                      ),
                      ValueListenableProvider.value(
                        value: _sexualError,
                        builder: (context, _) {
                          String error = context.watch<String>();
                          return _renderTextField(context, StringResources.xing_bie,
                              StringResources.qing_xuan_ze_xing_bie, _sexual, 'xingbie',
                              error: error, isSelectMode: true);
                        },
                      ),
                      Padding(
                        padding: EdgeInsets.only(left: 35.w),
                        child: Divider(
                          height: 1,
                        ),
                      ),
                      _renderSubmit(context, portrait),
                    ],
                  ),
                );
              }
              if (state == BaseState.EMPTY) {
                return EmptyWidget();
              }
              if (state == BaseState.FAIL) {
                return FailWidget(
                  onClick: () {
                    Provider.of<UserInfoEditViewModel>(context, listen: false).loadData();
                  },
                );
              }
              return Text('');
            },
            selector: (_, model) => model.mState),
      ),
    );
  }

  Widget _renderHeader(BuildContext context) {
    return GestureDetector(
      onTap: () {
        print('点击头像');
        _selectAvatar(context);
      },
      child: Container(
        margin: const EdgeInsets.only(top: 45, bottom: 50),
        child: Row(
          children: <Widget>[
            _renderAvatar(context),
            Expanded(child: renderNickname(context)),
          ],
        ),
      ),
    );
  }

  // 点击头像上传头像
  _selectAvatar(BuildContext context) async {
    var data = await _chicePhoto(context);
    var _imgPath;
    if (data != null && data == 'Photo') {
      var image = await ImagePicker()
          .getImage(source: ImageSource.camera, imageQuality: 80, maxHeight: 500, maxWidth: 500);
      _imgPath = image;
    } else if (data != null && data == 'Gallery') {
      var image = await ImagePicker()
          .getImage(source: ImageSource.gallery, imageQuality: 80, maxHeight: 500, maxWidth: 500);
      _imgPath = image;
    } else {
      return false;
    }

    String fileName = _imgPath.path.split('/').last;

    FormData formData = FormData.fromMap({
      "portrait": await MultipartFile.fromFile(
        _imgPath.path,
        filename: fileName,
      ),
    });

    Provider.of<UserInfoEditViewModel>(context, listen: false).modifyPortrait(formData,
        success: () {
      user.portrait =
          Provider.of<UserInfoEditViewModel>(context, listen: false).userInfoEdit.portrait;
      _imgPath = null;
      Toast.show('上传成功', context);
    }, onError: (error) {
      _imgPath = null;
      Toast.show('上传失败', context);
    });
  }

  _renderContainer(
      {String text,
      Color bgc = Colors.white,
      bool hasBorder = false,
      Color textColor = const Color(0xFF000000),
      double fontSize = 16}) {
    return Container(
      height: 63,
      alignment: Alignment.center,
      decoration: BoxDecoration(
          color: bgc,
          border:
              Border(bottom: BorderSide(color: Color(0xFFF6F6F7), width: hasBorder ? 0.5 : 0.0))),
      child: Text(text,
          style: TextStyle(
              color: textColor, fontWeight: FontWeight.w500, fontSize: fontSize, height: 1)),
    );
  }

  _chicePhoto(BuildContext context) async {
    return await showModalBottomSheet(
      context: context,
      elevation: 0,
      builder: (context) {
        return Container(
          height: 190,
          child: ListView(
            children: <Widget>[
              _renderContainer(
                  text: '请选择照片或拍照', fontSize: 14, textColor: Color(0xFF82868E), hasBorder: true),
              GestureDetector(
                onTap: () {
                  Navigator.pop(context, 'Photo');
                },
                child: _renderContainer(
                  text: '拍照',
                  fontSize: 16,
                ),
              ),
              GestureDetector(
                onTap: () {
                  Navigator.pop(context, 'Gallery');
                },
                child: _renderContainer(
                  text: '照片',
                  fontSize: 16,
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  // 头像
  Widget _renderAvatar(BuildContext context) {
    var userInfoEdit = Provider.of<UserInfoEditViewModel>(context, listen: false).userInfoEdit;
    return Stack(
      children: <Widget>[
        userInfoEdit.portrait != null
            ? ClipRRect(
                borderRadius: BorderRadius.circular(158.w),
                child: Selector<UserInfoEditViewModel, String>(
                    builder: (_, portrait, __) {
                      return CachedNetworkImage(
                        imageUrl: ImageUrlUtil.getClean(portrait, w: 150),
                        height: 158.w,
                        width: 158.w,
                        fit: BoxFit.cover,
                      );
                    },
                    selector: (_, model) => model.userInfoEdit.portrait),
              )
            : SizedBox.shrink(),
        Positioned(
          bottom: 0,
          right: 0,
          child: GestureDetector(
            onTap: () {
              print('xxx');
            },
            child: Container(
              width: 21,
              height: 21,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.all(Radius.circular(50)),
                  border: Border.all(width: 0.5, color: Color(0xFFD9DADA))),
              child: Image.asset(
                'images/mine_photo_grey.png',
                width: 15,
              ),
            ),
          ),
        )
      ],
    );
  }

  // 昵称
  Widget renderNickname(BuildContext context) {
    return GestureDetector(
      onTap: () {
        print('编辑昵称');
        _editNickname(context);
      },
      child: Container(
        height: 80.h,
        margin: const EdgeInsets.only(left: 19, right: 9),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Expanded(
              child: ValueListenableProvider.value(
                value: _nicknameNotifier,
                builder: (context, _) {
                  return GestureDetector(
                    onTap: () {
                      _editNickname(context);
                    },
                    child: Text(context.watch<String>(),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            color: Color(0xFF000000),
                            fontSize: 48.sp,
                            fontWeight: FontWeight.w600,
                            height: 1)),
                  );
                },
              ),
            ),
//            Expanded(
//              child: TextField(
//                readOnly: true,
//                style: TextStyle(
//                    color: Color(0xFF000000),
//                    fontSize: 48.sp,
//                    fontWeight: FontWeight.w600,
//                    height: 1),
//                decoration: InputDecoration(
//                  isDense: true,
//                  contentPadding: const EdgeInsets.fromLTRB(0, 0, 0, 0),
//                  border: OutlineInputBorder(
//                    borderSide: BorderSide(color: Colors.white, width: 0),
//                  ),
//                  focusedBorder: OutlineInputBorder(
//                      borderSide: BorderSide(color: Colors.white, width: 0),
//                      borderRadius: BorderRadius.all(Radius.circular(0))),
//                  enabledBorder: OutlineInputBorder(
//                      borderSide: BorderSide(color: Colors.white, width: 0),
//                      borderRadius: BorderRadius.all(Radius.circular(0))),
//                ),
//                controller: _nickname,
//                onTap: () {
//                  _editNickname(context);
//                },
//              ),
//            ),
            Image.asset('images/mine_file_edit.png', width: 15)
          ],
        ),
      ),
    );
  }

  void _editNickname(BuildContext context) async {
    String result = await showShareDialog(context);
    if (result != null && result.trim() != '') {
      Provider.of<UserInfoEditViewModel>(context, listen: false).modifyNickname(result,
          success: () {
            user.nickname = result;
            _nicknameNotifier.value = result;
          },
          onError: (msg) => Toast.show(msg, context));
    }
  }

  Future showShareDialog(BuildContext context) async {
    RegExp nickNameReg = new RegExp(r'^.{2,10}$');
    TextEditingController _nicknameEdit = TextEditingController();
    return await showDialog(
      context: context,
      builder: (context) {
        var child = Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Container(
              margin: const EdgeInsets.only(top: 16),
              child: Text('修改昵称', style: TextStyle(fontSize: 15)),
            ),
            Container(
              alignment: Alignment.center,
              color: Theme.of(context).backgroundColor,
              margin: const EdgeInsets.fromLTRB(11.5, 27.5, 11.5, 0),
              child: Form(
                autovalidate: true,
                child: TextFormField(
                  style: TextStyle(color: Theme.of(context).textTheme.subtitle2.color),
                  autofocus: true,
                  keyboardType: TextInputType.text,
                  decoration: InputDecoration(
                    contentPadding: EdgeInsets.all(10.0),
                    hintText: '请输入昵称',
                    hintStyle: TextStyle(color: Colors.black12, fontSize: 12),
                  ),
                  controller: _nicknameEdit,
                  validator: (v) {
                    return v.trim().length > 0 ? null : "昵称不能为空";
                  },
                  onChanged: (v) {},
                ),
              ),
            ),
            Container(
              height: 30,
              alignment: Alignment.center,
              margin: const EdgeInsets.fromLTRB(0, 30, 0, 6),
              child: Row(
                mainAxisSize: MainAxisSize.max,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Expanded(
                    child: GestureDetector(
                      onTap: () {
                        Navigator.of(context).pop();
                      },
                      child: Container(
                        alignment: Alignment.center,
                        child: Text(
                          '取消',
                          style: TextStyle(fontSize: 13),
                        ),
                      ),
                    ),
                  ),
                  Container(
                    height: 30,
                    width: 2,
                    color: Color(0xFFEBECF1),
                  ),
                  Expanded(
                    child: GestureDetector(
                      onTap: () {
                        var str = _nicknameEdit.text.trim();
                        if (nickNameReg.hasMatch(str)) {
                          Navigator.of(context).pop(str);
                        } else {
                          Toast.show("昵称不得小于2位/小于16位", context);
                        }
                      },
                      child: Container(
                        alignment: Alignment.center,
                        child: Text(
                          '确定',
                          style: TextStyle(color: Color(0xFF0CABCB), fontSize: 13),
                        ),
                      ),
                    ),
                  )
                ],
              ),
            ),
          ],
        );
        return Dialog(child: child);
      },
    );
  }

  //选择省市区
  Widget _selectAddress(BuildContext context) {
    return GestureDetector(
      onTap: () {
        showAddressDialog(context);
      },
      child: Container(
        padding: EdgeInsets.fromLTRB(35.w, 45.h, 35.w, 45.h),
        child: Row(
          children: <Widget>[
            Expanded(
              child: ValueListenableProvider<String>.value(
                value: _cityError,
                builder: (context, _) {
                  return Text(
                    context.watch<String>(),
                    style: TextStyle(
                        fontSize: 28.sp, color: Theme.of(context).textTheme.subtitle2.color),
                  );
                },
              ),
            ),
            Icon(
              Icons.navigate_next,
              color: Color(0xFF82868E),
            )
          ],
        ),
      ),
    );
  }

  void showAddressDialog(BuildContext context) {
    List data = Provider.of<UserInfoEditViewModel>(context, listen: false).data;
    var userInfoEdit = Provider.of<UserInfoEditViewModel>(context, listen: false).userInfoEdit;
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return AddressDialog(
            data,
            onSelected: (province, city, county) {
              var address = '$province $city $county';
              userInfoEdit.city = address;
              _city.text = address;
            },
            title: '选择地区',
            unselectedColor: Color(0xFF333333),
            itemTextFontSize: 28.sp,
          );
        });
  }

  _renderSubmit(BuildContext context, String portrait) {
    var userInfoEdit = Provider.of<UserInfoEditViewModel>(context, listen: false).userInfoEdit;
    return GestureDetector(
      onTap: () {
        print('提交个人资料');
        RegExp emailReg =
            new RegExp(r'^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$');
        if (_email.text != null && !emailReg.hasMatch(_email.text)) {
          _emailError.value = '邮箱格式有误';
          return;
        }
        if (_city.text == '') {
          _cityError.value = '城市信息不能为空';
          return;
        }
        if (_sexual.text.trim() == '') {
          _sexualError.value = '性别信息不能为空';
          return;
        }

        userInfoEdit.portrait = portrait;
        userInfoEdit.nickname = _nicknameNotifier.value;
        userInfoEdit.company = _company.text;
        userInfoEdit.position = _position.text;
        userInfoEdit.email = _email.text;
        userInfoEdit.sign = _sign.text;
        userInfoEdit.city = _city.text;
        userInfoEdit.sexual = getSex(_sexual.text);

        Provider.of<UserInfoEditViewModel>(context, listen: false).modifyUserInfo(userInfoEdit,
            success: () {
          Navigator.of(context).pop({'name': _nicknameNotifier.value, 'portrait': portrait});
        });
      },
      child: Container(
        margin: const EdgeInsets.only(bottom: 50, top: 40),
        height: 48,
        color: Color(0xFF0CABCB),
        alignment: Alignment.center,
        child: Text('完成',
            style: TextStyle(
                color: Color(0xFFF7F8F8), fontSize: 30.sp, fontWeight: FontWeight.w500, height: 1)),
      ),
    );
  }

  _renderTextField(BuildContext context, String title, String hintText,
      TextEditingController controller, String key,
      {inputType,
      keyType,
      expand,
      String error,
      isMaxLines = false,
      bool isRequired = true,
      bool hasRightBar = true,
      bool isSelectMode = false}) {
    return Container(
      padding: const EdgeInsets.only(right: 0, top: 19.5),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          _renderTitle(text: title, isSelectMode: isSelectMode),
          Container(
            padding: EdgeInsets.only(bottom: 20.h),
            decoration: BoxDecoration(
              color: Color(0xFFFFFFFF),
              border: Border(
                bottom: BorderSide(color: Colors.lightBlueAccent),
              ),
            ),
            child: TextField(
              style: TextStyle(
                fontSize: 28.sp,
                color: Theme.of(context).textTheme.subtitle2.color,
              ),
              readOnly: isSelectMode ? true : false,
              controller: controller,
              keyboardType: keyType,
              inputFormatters: inputType,
              onTap: !isSelectMode
                  ? null
                  : () {
                      _onTapItem(context, controller, key);
                    },
              decoration: InputDecoration(
                contentPadding: EdgeInsets.all(0),
                isDense: true,
                border: InputBorder.none,
                hintText: hintText,
              ),
            ),
          ),
          error != null && error.trim() != ''
              ? Text(
                  error,
                  style: TextStyle(fontSize: 28.sp, color: Colors.red),
                )
              : Constants.empty,
        ],
      ),
    );
  }

  _renderTitle({String text, bool isRequired = false, bool isSelectMode = false}) {
    return Container(
      child: Row(
        children: <Widget>[
          Expanded(
            child: Text.rich(
              TextSpan(children: <TextSpan>[
                isRequired
                    ? TextSpan(
                        text: '* ', style: TextStyle(fontSize: 32.sp, color: Color(0xFF0CABCB)))
                    : TextSpan(text: ''),
                TextSpan(
                    text: text,
                    style: TextStyle(
                        color: Color(0xFF000000),
                        fontSize: 32.sp,
                        fontWeight: FontWeight.w600,
                        height: 1)),
              ]),
            ),
          ),
          isSelectMode ? Image.asset('images/ic_prev_black.png', width: 10.5) : SizedBox.shrink()
        ],
      ),
      margin: const EdgeInsets.only(bottom: 11.5),
    );
  }

  _onTapItem(context, controller, key) async {
    if (key == 'chengshi') {
      print('选择城市');
      showAddressDialog(context);
    } else if (key == 'xingbie') {
      print('点击选择性别');
      var data = await _chiceGender(context);
      print('选择对象男女');
      print(map[data]);
      if (data != null) {
        _sexual.text = map[data];
      }
    }
  }

  _chiceGender(BuildContext context) async {
    return await showModalBottomSheet(
      context: context,
      elevation: 0,
      builder: (context) {
        return Container(
          child: ListView(
            children: <Widget>[
              _renderOptions(text: '请选择', hasBottomLine: true),
              GestureDetector(
                onTap: () {
                  Navigator.pop(context, '1');
                },
                child: _renderOptions(text: '男', hasBottomLine: false),
              ),
              GestureDetector(
                onTap: () {
                  Navigator.pop(context, '2');
                },
                child: _renderOptions(text: '女', hasBottomLine: false),
              ),
            ],
          ),
        );
      },
    );
  }

  _renderOptions({String text, bool hasBottomLine = false}) {
    return Container(
      padding: const EdgeInsets.fromLTRB(17.5, 14.5, 17.5, 14.5),
      decoration: hasBottomLine
          ? BoxDecoration(
              color: Colors.white,
              border: Border(bottom: BorderSide(color: Color(0xFFE5E7E8), width: 0.5)))
          : null,
      child: Text(text,
          style: TextStyle(
              color: Color(0xFF000000), fontWeight: FontWeight.w500, fontSize: 12, height: 1)),
    );
  }

  String getSex(String text) {
    if (text == '男') {
      return '1';
    } else if (text == '女') {
      return '2';
    } else {
      return '0';
    }
  }
}
